module.exports = (EdtApi) => {
  "use strict";
  let chatId = "";
  async function getChatId(times = 0) {
    let id = window.location.hash?.replace("#", "") || "";
    if (id && id != chatId) return id;
    await EdtApi.sleep(50);
    if (times > 10) return id;
    times++;
    return getChatId(times);
  }
  function getNodeContent(node) {
    let text = "";
    switch (node.nodeName) {
      case "#text":
        text = node.textContent;
        break;
      case "IMG":
        text = node.alt;
        break;
      case "BR":
        text = "\n";
        break;
      case "A":
        text = node.textContent;
        break;
      case "STRONG":
        node.childNodes?.forEach((child) => {
          text += getNodeContent(child);
        });
        break;
      default:
        break;
    }
    return text;
  }
  return {
    config: {
      friendList: ".Transition_slide.Transition_slide-active .chat-list,.Transition_slide.Transition_slide-active .search-section,.Transition_slide.Transition_slide-active .search-content,.top-peers-section>.top-peers",
      chat: "#MiddleColumn div.messages-layout",
      input: 'div.messages-layout div.Transition div.Transition_slide.Transition_slide-active div.form-control[contenteditable][role="textbox"]',
      unread: "#LeftColumn-main .ListItem .subtitle .unread:not(.muted)",
      msgBox: ".messages-layout .Transition_slide-active .MessageList",
      inMsg: "div.MessageList .message-list-item:not(.own) .content-inner:not(.trans-inited)",
      outMsg: "div.MessageList .message-list-item.own .content-inner:not(.trans-inited)",
      voiceMsg: '.message-content.voice .Audio:not(.trans-inited)',
      sendBtn: "div.Transition_slide-active div.Composer>button.Button.send",
      setting: ".messages-layout div.Transition_slide.Transition_slide-active div.middle-column-footer div.message-input-wrapper #message-input-text",
      files: {
        sendBtn: "div.Modal.open div.wDqWK9MD>button.Button",
        event: "mousedown",
      },
      tips: {
        in: "div.MiddleHeader div.Transition_slide.Transition_slide-active .chat-info-wrapper>div.ChatInfo>div.info",
        out: "div.Transition>div.Transition_slide.Transition_slide-active>div.middle-column-footer",
      },
      placeholder: {
        selector: "div.messages-layout>div.Transition>div.Transition_slide.Transition_slide-active .placeholder-text",
      },
      userInfo: {
        selector: "div.MenuItem",
        level: 3,
      },
      contextmenu: false,
      inputType: "input",
      extra: {//其他会触发对话框变动的情况处理
        selector: ".back-button,.text-entity-link,.message-title,.members-list,.Avatar",
        level: 5,
        delay: 500,
      },
    },
    getChatInfo() {
      return new Promise(async (resolve) => {
        chatId = await getChatId();
        resolve({ id: chatId, isGroup: chatId?.includes("-") });
        this.scrollToBottom();
      });
    },
    getChatTitle(chatEl = document) {
      let titleEl = chatEl.querySelector(
        "div.MiddleHeader div.Transition_slide.Transition_slide-active .chat-info-wrapper>div.ChatInfo>div.info>div.title>h3"
      );
      if (!titleEl) return "";
      if (!titleEl.querySelector(".emoji")) return titleEl.textContent || "";
      let title = "";
      titleEl.childNodes?.forEach((child) => {
        if (child.nodeName == "#text") {
          title += child.textContent || "";
        } else if (child.nodeName == "IMG") {
          title += child.alt || "";
        }
      });
      return title;
    },
    getText(msgBox) {
      let texts = [],
        text = "";
      try {
        let textEls = msgBox.querySelectorAll(
          ".text-content,.site-title,.site-description"
        );
        textEls?.forEach((el) => {
          text = "";
          el.childNodes?.forEach((child) => {
            text += getNodeContent(child);
          });
          texts.push(text);
        });
      } catch (error) {
        console.error(error);
      }
      return texts.join("\n");
    },
    getIptMsg(inputEl) {
      if (!inputEl) return "";
      let value = "";
      try {
        inputEl.childNodes?.forEach((child) => {
          if (child.nodeName == "#text") {
            value += child.textContent;
          } else if (child.nodeName == "IMG") {
            value += child.alt;
          } else if (child.nodeName == "BR") {
            value += "\n";
          }
        });
      } catch (error) {
        console.error(error);
      }
      return value;
    },
    beforeSend({ handler }) {
      //发送前处理特殊情况
      let obj = {
        result: true,
        fileInput: null,
      };
      return new Promise((resolve) => {
        let fileModal = document.querySelector("#portals div.Modal.open");
        if (!fileModal) return resolve(obj);
        let fileInput = fileModal.querySelector("#editable-message-text-modal");
        if (!fileInput) return resolve(obj);
        obj.fileInput = fileInput;
        let msg = this.getIptMsg(fileInput);
        if (!handler.sendTrans(msg)) return resolve(obj);
        handler.transToInput(fileInput, msg).then((result) => {
          obj.result = result;
          resolve(obj);
        }).catch((error) => {
          handler.showLoading({
            msg: error.message || "翻译失败！",
            type: "error",
          });
          obj.result = false;
          resolve(obj);
        });
      });
    },
    scrollToBottom() {
      let searchEl = document.querySelector(".Transition .LeftSearch");
      if (searchEl) return;
      let num = 0, el, timer = setInterval(() => {
        el = document.querySelector(".MessageList");
        if (el) el.scrollTop = el.scrollHeight;
        num++;
        if (num >= 2) {
          clearInterval(timer);
          timer = null;
          el = null;
        }
      }, 200);
    },
    handlerUserInfo() {
      EdtApi.queryWait({ selector: "#Settings", timeout: 60000 })
        .then(async (view) => {
          if (view) {
            let avatarEl = view.querySelector("div.ProfilePhoto>img.thumb");
            let avatar = avatarEl?.getAttribute("src") || "";
            if (avatar && avatar.startsWith("blob:")) {
              avatar && (avatar = await EdtApi.urlToDataUrl(avatar));
            }
            let globalData = JSON.parse(
              localStorage.getItem("tt-global-state") || "{}"
            );
            let userId = globalData?.currentUserId;
            let info = globalData?.users?.byId?.[userId];
            let account = info?.phoneNumber || "";
            let userName = "";
            if (info.usernames?.length > 0) {
              userName = info.usernames[0].username;
            }
            if (!userName) {
              userName = `${info.firstName}${info.lastName ? "-" + info.lastName : ""
                }`;
            }
            let userInfo = {
              avatar,
              userName,
              account,
            };
            localStorage.setItem("user-info", JSON.stringify(userInfo));
            EdtApi.sendToHost("user-info", userInfo);
          }
        })
        .catch(() => { });
    },
    getUserInfo() {
      try {
        let userInfo = localStorage.getItem("user-info");
        if (userInfo) {
          return JSON.parse(userInfo);
        } else {
          let globalData = JSON.parse(
            localStorage.getItem("tt-global-state") || "{}"
          );
          let userId = globalData?.currentUserId;
          let info = globalData?.users?.byId?.[userId];
          let fullInfo = globalData?.users?.fullInfoById?.[userId];
          let account = info?.phoneNumber || "";
          let avatar = fullInfo?.profilePhoto?.thumbnail?.dataUri || "";
          let userName = "";
          if (info?.usernames?.length > 0) {
            userName = info.usernames[0].username;
          }
          if (!userName) {
            userName = `${info?.firstName}${info?.lastName ? "-" + info?.lastName : ""
              }`;
          }
          return {
            avatar,
            userName,
            account,
          };
        }
      } catch (error) {
        return null;
      }
    }
  };
};